# -*- coding:UTF-8 -*-
from socket import *
import json


class UdpHelper:
    def __init__(self):
        self.udp_socket = socket(AF_INET, SOCK_DGRAM)
        local_addr = ('', 12000)  # ip地址和端口号，ip一般不用写，表示本机的任何一个ip
        self.udp_socket.bind(local_addr)
        self.recv_data = None
    
    def run(self):
        # 等待接收对方发送的数据
        while True:
            self.recv_data = self.udp_socket.recvfrom(1024)  # 1024表示本次接收的最大字节数
            if self.recv_data is not None:
                que_dict = {'json_data': None}
                from filter.udpfilter import g_filter_route as udpfilters
                is_filter = udpfilters["json"](self.recv_data, que_dict) and udpfilters[
                    "is_recv"](self.recv_data, que_dict)
                if is_filter: break
        recv_str = self.recv_data[0].decode('utf-8')
        self.recv_data = None
        print(recv_str)
        return recv_str
    
    def close(self):
        self.udp_socket.close()
        print("udp server is close")


if __name__ == '__main__':
    udp_hlpr = UdpHelper()
    udp_hlpr.run()
    udp_hlpr.close()
